<script lang="ts">
  import { Modal } from "@skeletonlabs/skeleton-svelte";
  import {
    list_server,
    save_server_list,
    type ServerInfo,
  } from "$lib/api/client_cfg";
  import { X } from "lucide-svelte";
  import { getContext } from "svelte";
  import { conn_grpc_server } from "$lib/api/main";
  import { appStore } from "$lib/stores/app.svelte";
  import { userStore } from "$lib/stores/user.svelte";
  import type { Store as ToastStore } from "@zag-js/toast";

  const toast: ToastStore = getContext("toast");

  let props: { onClose: () => void } = $props();

  let serverList = $state([] as ServerInfo[]);

  let newServerAddr = $state("");

  async function loadServerList() {
    const res = await list_server();
    serverList = res.server_list;
  }

  async function addServer() {
    if (!newServerAddr.includes(":")) {
      return;
    }
    const tmpList = serverList.slice();
    if (tmpList.find((item) => item.addr == newServerAddr) != undefined) {
      toast.create({
        title: "失败",
        description: "服务器已经存在!",
        type: "error",
      });
      return;
    }
    tmpList.push({
      name: newServerAddr,
      system: false,
      addr: newServerAddr,
      default_server: false,
    });
    await save_server_list(tmpList);
    newServerAddr = "";
    await loadServerList();
    toast.create({
      title: "成功",
      description: "增加服务器成功!",
      type: "success",
    });
  }

  async function setDefaultServer(addr: string) {
    const tmpList = serverList.slice();
    for (const server of tmpList) {
      if (server.addr == addr) {
        server.default_server = true;
      } else {
        server.default_server = false;
      }
    }
    await save_server_list(tmpList);
    await loadServerList();
    toast.create({
      title: "成功",
      description: "设置默认服务器成功!",
      type: "success",
    });

    const connRes = await conn_grpc_server(addr);
    if (connRes) {
      toast.create({
        title: "成功",
        description: "连接默认服务器成功!",
        type: "success",
      });
    } else {
      toast.create({
        title: "错误",
        description: "连接默认服务器失败!",
        type: "error",
      });
    }
    await appStore.initServerCfg();
  }

  async function removeServer(addr: string) {
    const tmpList = serverList.filter((item) => item.addr != addr);
    await save_server_list(tmpList);
    await loadServerList();
    toast.create({
      title: "成功",
      description: "删除服务器成功!",
      type: "success",
    });
  }

  loadServerList();
</script>

<Modal
  open={true}
  triggerBase="btn preset-tonal"
  contentBase="card bg-surface-200-800 p-4 space-y-4 shadow-xl w-[500px]"
  backdropClasses="backdrop-blur-xs"
  backdropBase="backdrop-none"
  onOpenChange={(ev) => {
    if (!ev.open) {
      props.onClose();
    }
  }}
>
  {#snippet content()}
    <header class="flex justify-between">
      <h4 class="h4">应用配置</h4>
      <button
        type="button"
        class="btn preset-ghost-primary-500"
        onclick={() => props.onClose()}
      >
        <X />
      </button>
    </header>

    <div class="w-full max-h-[50vh] overflow-y-auto pl-0">
      <h4 class="h4">服务器配置</h4>
      <label class="label relative p-2">
        <span class="label-text">当前服务器</span>
        <select
          class="select rounded-none bg-surface-100-900"
          value={serverList.find((item) => item.default_server)?.addr ?? ""}
          disabled={userStore.userSession != ""}
          onchange={(e) => setDefaultServer(e.currentTarget.value)}
        >
          {#each serverList as server}
            <option value={server.addr}>
              {server.addr}
            </option>
          {/each}
        </select>
      </label>

      <h5 class="h5">服务器列表</h5>
      <ul>
        {#each serverList as server}
          <li class={`flex border-b-[1px] border-surface-300-700`}>
            <div class="flex-1 text-xl p-2 leading-4">
              {server.addr}
            </div>

            <div class="flex space-x-2 justify-end">
              {#if !server.default_server && !server.system}
                <button
                  type="button"
                  class="btn preset-ghost-error-500 text-error-500 p-0"
                  onclick={() => removeServer(server.addr)}>删除服务器</button
                >
              {/if}
            </div>
          </li>
        {/each}
      </ul>

      {#if userStore.userSession == ""}
        <div class="flex my-[10px] space-x-4 pl-2">
          <div class="flex-1">
            <input
              bind:value={newServerAddr}
              type="text"
              placeholder="请输入服务器地址"
              class="input w-full rounded-none bg-surface-100-900"
            />
            <div class="h-[1em] text-warning-900-100">
              {#if !newServerAddr.includes(":")}
                请输入 主机名:端口
              {/if}
            </div>
          </div>
          <button
            type="button"
            class="btn preset-filled-primary-500 h-[30px]"
            disabled={!newServerAddr.includes(":")}
            onclick={() => addServer()}>增加</button
          >
        </div>
      {/if}
    </div>
  {/snippet}
</Modal>
